package com.hundsun.openservice.sdk;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class ResultParser {

    private ResultParser() {
    }

    private static final String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss.SSS+08:00";

    private static ThreadLocal<DateFormat> FORMAT_THREAD_LOCAL = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(DATE_FORMAT_STRING);
        }
    };

    /**
     * 
     * 
     * @param  dayType: 1、年月 2、年 3、年月日
     * @return TODO 返回说明
     * @throws TODO 异常信息
     */
    public static JSONArray parseResult(JSONObject result, String[] statsFields, String mertric, String dayType) {
        JSONArray resultArray = new JSONArray();
        // aggregations-request-bucket
        JSONObject aggrResult = result.getJSONObject("aggregations");
        if (aggrResult != null) {
            // 取聚合
            JSONObject dateResult = aggrResult.getJSONObject("time");
            if (dateResult != null) {
                JSONArray dateBucket = dateResult.getJSONArray("buckets");
                for (int i = 0; i < dateBucket.size(); i++) {
                    JSONObject resultJson = new JSONObject();
                    JSONObject dateJson = dateBucket.getJSONObject(i);
                    resultJson.put("date", formatTime(dayType, dateJson.getString("key_as_string")));
                    JSONArray fieldBucket = dateJson.getJSONObject(statsFields[0]).getJSONArray("buckets");
                    resultJson.put(statsFields[0], parseBuckets(fieldBucket, 0, statsFields, mertric));
                    resultArray.add(resultJson);
                }
            } else {
                resultArray = parseBuckets(aggrResult.getJSONObject(statsFields[0]).getJSONArray("buckets"), 0,
                        statsFields, mertric);
            }
        } else {
            // 取hits

        }
        return resultArray;
    }

    public static JSONArray parseBuckets(JSONArray buckets, int fieldIndex, String[] statsFields, String mertric) {
        if (StringUtils.isEmpty(mertric)) {
            mertric = "count";
        }
        JSONArray dataArray = new JSONArray();
        for (int i = 0; i < buckets.size(); i++) {
            JSONObject resultJson = new JSONObject();
            JSONObject bucketJson = buckets.getJSONObject(i);
            resultJson.put(statsFields[fieldIndex], bucketJson.getString("key"));
            if (fieldIndex + 1 < statsFields.length) {
                resultJson.put(statsFields[fieldIndex + 1],
                        parseBuckets(bucketJson.getJSONObject(statsFields[fieldIndex + 1]).getJSONArray("buckets"),
                                fieldIndex + 1, statsFields, mertric));
            } else {
                JSONObject numeric_stat = bucketJson.getJSONObject("numeric_stat");
                JSONObject numeric_stat2 = bucketJson.getJSONObject("numeric_stat2");
                double num = Double.parseDouble(numeric_stat.getString("value_as_string") == null
                        ? numeric_stat.getString("value") : numeric_stat.getString("value_as_string"));
                if (numeric_stat2 != null) {
                    String num2Str = numeric_stat2.getString("value_as_string") == null
                            ? numeric_stat2.getString("value") : numeric_stat2.getString("value_as_string");
                    DecimalFormat df_general = new DecimalFormat("########0.00");
                    double num2 = Double.parseDouble(num2Str);
                    if (num2 != 0.00) {
                        resultJson.put(mertric, df_general.format(num / num2));
                    }
                } else {
                    resultJson.put(mertric, numeric_stat.get("value_as_string") == null ? numeric_stat.get("value")
                            : numeric_stat.get("value_as_string"));
                }
            }
            dataArray.add(resultJson);
        }
        return dataArray;
    }

    /**
     * 格式化时间格式
     * @param  dayType: 1、年月 2、年 3、年月日
     * @return 返回值
     */
    private static String formatTime(String dayType, String time) {
        String formatedTime = "";
        String formatter = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        Date date = null;
        try {
            date = FORMAT_THREAD_LOCAL.get().parse(time);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        switch (dayType) {
        case "month":
            formatter = "yyyy-MM";

            break;
        case "year":
            formatter = "yyyy";
            break;
        case "day":
            formatter = "yyyy-MM-dd";
            break;
        default:
            break;
        }
        sdf.applyPattern(formatter);
        formatedTime = sdf.format(date);

        return formatedTime;
    }

    // public JSONArray getAllFields(JSONArray totalArray,JSONObject
    // preJson,JSONArray thisArray,int index,String[] statFields){
    // for(int i = 0;i<thisArray.size();i++){
    // JSONObject thisJson = thisArray.getJSONObject(i);
    // JSONObject thisObject = (JSONObject) preJson.clone();
    // thisObject.put(statFields[index], thisJson.get(statFields[index]));
    // if(index+1<statFields.length){
    // JSONArray nextArray = thisJson.getJSONArray(statFields[index+1]);
    // for(int j = 0;j<nextArray.size();j++){
    // getAllFields(totalArray,thisObject,nextArray,index+1,statFields);
    // }
    // }else{
    // totalArray.add(thisObject);
    // }
    //
    // }
    //
    //
    //
    // return totalArray;
    // }

}
